package ks.server.controllers;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.debug.Debug;
import ks.framework.interfaces.IProcessMessage;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class ChatController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public ChatController (Communicator com) {
		this.com = com;
	}
	
	public boolean process(Message m) {
		Node text = m.contentsChild();
        String s = text.getTextContent();
        
        Debug.println ("found on server:" + s);
        
        // produce request.
        StringBuilder sb = new StringBuilder("<request version='1.0' id='1'><output><text>");
        sb.append(m.getOriginator()).append(": ").append(s);
        sb.append("</text></output></request>");
        Document d = Message.construct(sb.toString());
        
        // send to all clients EXCEPT self.
        Message r = new Message (d);
        r.setBroadcast();
        
        com.distribute(r);
        return true;
	}
}
